package com.ctrip.ibu.member.nameservice.controller;


import com.ctrip.ibu.member.common.result.HandleResult;
import com.ctrip.ibu.member.nameservice.module.AllBrokerBriefInfo;
import com.ctrip.ibu.member.nameservice.module.BrokerInfo;
import com.google.common.collect.Sets;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.net.UnknownHostException;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @author he.shaorong
 * @create 2023/3/27 15:26
 * @since 1.0.0
 */
@Api(description ="nameserver")
@RestController
public class NameServerController {
    private static final Logger logger = LoggerFactory.getLogger(NameServerController.class);

    private static Set<String> aliveIpList = Sets.newConcurrentHashSet();

    @ApiOperation("测试nameserver")
    @GetMapping(value = "/testController")
    public String testController() {
        return "SUCCESS!";
    }

    @ApiOperation("测试nameserver")
    @GetMapping(value = "/isNameServerAlive")
    public String isNameServerAlive() {
        return "SUCCESS!";
    }


    @ApiOperation("获取所有存活的broker信息")
    @GetMapping(value = "/getAliveBrokerList")
    public AllBrokerBriefInfo getAliveBrokerList() throws UnknownHostException {
        logger.info("getAliveBrokerList aliveIpList:" + aliveIpList.toString());
        return new AllBrokerBriefInfo(aliveIpList.stream().map(item -> new BrokerInfo(item)).collect(Collectors.toList()));
    }

    @ApiOperation("注册broker")
    @PostMapping(value = "/registerBroker")
    public synchronized HandleResult registerBroker(@RequestBody BrokerInfo brokerInfo) {
        // todo ip校验
        if (Objects.nonNull(brokerInfo) && Objects.nonNull(brokerInfo.getIp())) {
            aliveIpList.add(brokerInfo.getIp());
            logger.info("registerBroker success ip:" + brokerInfo.getIp());
            return new HandleResult(true);
        }
        logger.info("registerBroker failed brokerInfo:" + brokerInfo.toString());
        return new HandleResult(false);
    }

    public static Set<String> getAliveIpList() {
        return aliveIpList;
    }
}
